package com.feige.config;

import cn.hutool.core.util.ObjectUtil;
import com.feige.annotation.LoginUser;
import com.feige.utils.http.ResponseUtil;
import com.feige.utils.http.ServletUtils;
import com.feige.utils.jwt.JwtInfo;
import com.feige.utils.jwt.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author feige<br />
 * @ClassName: TokenMethodArgumentResolver <br/>
 * @Description: <br/>
 * @date: 2022/3/29 23:52<br/>
 */
@Component
public class TokenMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        LoginUser loginUser = parameter.getParameterAnnotation(LoginUser.class);
        if (ObjectUtil.isNotNull(loginUser)){
            HttpServletRequest request = ServletUtils.getRequest();
            HttpServletResponse response = ServletUtils.getResponse();
            JwtInfo jwtInfo = jwtUtils.getJwtInfoByToken(request);
            if (ObjectUtil.isNull(jwtInfo) && loginUser.required()){
                ResponseUtil.outError(response);
            }
            return jwtInfo;
        }
        return null;
    }
}
